package com.zdw.test3;

import com.zdw.test2.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Author: Zhang Dongwei
 * Date: 2022/4/3 19:52
 * sql注入
 */
public class SQLInjection {
    public static void main(String[] args) {
//        正常登录
//        login("lisi","123456");

        //SQL注入
        login("' or '1=1","'or'1=1");
    }
    // 登录业务
    public static void login(String username,String password){
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();

            // sql
            // SELECT * FROM users WHERE `NAME`='lisi' AND `password` = '123456'  //正常
            // SELECT * FROM users WHERE `NAME`='' or '1=1' AND `password` = '123456'  //注入后的语句
            String sql = "select * from users where `NAME`=? and `PASSWORD`=?";

            st = conn.prepareStatement(sql);
            st.setString(1, username);
            st.setString(2, password);
            rs = st.executeQuery(); // 查询完毕会返回结果集

            while (rs.next()){
                System.out.println(rs.getString("NAME"));
                System.out.println(rs.getString("password"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JdbcUtils.release(conn,st,rs);
        }
    }
}
